def call(){
    println("this is in var k8s.groovy")
}

def sum(a, b)
{
    println a + b
}

def myPrint(context){
    println(context)
}

def HttpReq(reqType, reqUrl, reqBody, cType){
    def apiServer = "https://192.168.234.129:6443/apis/apps/v1"
    withCredentials([string(credentialsId: 'k8s-secret', variable: 'kubernetestoken')]) {
        result = httpRequest customHeaders: [[maskValue: true, name: 'Authorization', value: "Bearer ${kubernetestoken}"],[maskValue: false, name: 'Content-Type', value: "${cType}"], [maskValue: false, name: 'Accept', value: "application/yaml"]],
                   httpMode: reqType,
                   consoleLogResponseBody: true,
                   ignoreSslErrors: true,
                   requestBody: reqBody,
                   url: "${apiServer}/${reqUrl}"
    }
    return result
}

// 获取deployment
def GetDepolyment(nameSpace, deployName, interf){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    cType = "application/yaml"
    response = HttpReq('GET', apiUrl, '', cType)
    def datas = readYaml text: """${response.content}"""
    if(interf == "front"){
        img = (datas["spec"]["template"]["spec"]["initContainers"]["image"][0])
        containerName = (datas["spec"]["template"]["spec"]["initContainers"]["name"][0])
        def containerImg = img.split(':')[0]
        return [containerImg, containerName]
    }else{
        img = (datas["spec"]["template"]["spec"]["containers"]["image"][0])
        containerName = (datas["spec"]["template"]["spec"]["containers"]["name"][0])
        def containerImg = img.split(':')[0]
        return [containerImg, containerName]
    }
}

// 更新deployment
def UpdateDeployment(nameSpace, deployName, containerImg, containerName, imageVer, interf){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    cType = "application/strategic-merge-patch+json"
    if(interf == "front"){
        deployBody = """{"spec":{"template":{"spec":{"initContainers":[{"name":"${containerName}","image":"${containerImg}:${imageVer}"}]}}}}"""
    }else{
        deployBody = """{"spec":{"template":{"spec":{"containers":[{"name":"${containerName}","image":"${containerImg}:${imageVer}"}]}}}}"""
    }
    response = HttpReq('PATCH', apiUrl, deployBody, cType)
    println(response)
}

//获取deployment状态
def GetDeploymentStatus(nameSpace, deployName){
    apiUrl = "namespaces/${namespace}/deployments/${deployName}/status"
    cType = "application/merge-patch+json"
    response = HttpReq('GET', apiUrl, '', cType)
    println(response)
}